package com.hyd.hx_adr.utils;

import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;

/**
 * @author van
 * @create 2024-04-26 11:37
 */
public class Sm4Utils {

    private static SymmetricCrypto symmetricCrypto;

    private static String key = "b9cf72e515fac9b4";

    private static String algorithm = "SM4/ECB/PKCS5Padding";

    public static SymmetricCrypto getInstance(){
        if(symmetricCrypto==null){
            symmetricCrypto = new SymmetricCrypto(algorithm, key.getBytes());
        }
        return symmetricCrypto;
    }

    public static String encode(String text){
        if( ObjectUtils.isEmpty(text)){
            return null;
        }
        byte[] encrypt = getInstance().encrypt(text);
        return Base64Utils.encodeToString(encrypt);
    }

    public static String decode(String text){
        if( ObjectUtils.isEmpty(text)){
            return null;
        }
        byte[] bytes = Base64Utils.decodeFromString(text);
        byte[] decrypt = getInstance().decrypt(bytes);
        return new String(decrypt);
    }

    public static byte[] decodeWithBytes(byte[] bytes) {
       return getInstance().decrypt(bytes);
    }


    public static SymmetricCrypto newInstance(String algorithm, String key){
        return new SymmetricCrypto(algorithm, key.getBytes());
    }

    public static String encode(SymmetricCrypto crypto, String text, String key){
        if(crypto==null|| ObjectUtils.isEmpty(text)||ObjectUtils.isEmpty(key)){
            return null;
        }
        byte[] encrypt = crypto.encrypt(text);
        return Base64Utils.encodeToString(encrypt);
    }

    public static String decode(SymmetricCrypto crypto, String text, String key){
        if(crypto==null|| ObjectUtils.isEmpty(text)||ObjectUtils.isEmpty(key)){
            return null;
        }
        byte[] bytes = Base64Utils.decodeFromString(text);
        byte[] decrypt = crypto.decrypt(bytes);
        return new String(decrypt);
    }
}
